<?php

namespace Core\server;

use Core\BeanFactory;
use Core\init\RouterCollector;
use Core\process\FilesProcess;
use FastRoute\Dispatcher;
use Swoole\Http\Request;
use Swoole\Http\Response;
use Swoole\Server;

class HttpServer
{
    private $server;
    /**@var $dispatcher \FastRoute\Dispatcher* */
    private $dispatcher;

    public function __construct()
    {
        $this->server = new \swoole_http_server("location", 81);
        //默认开启两个worker_num 因此连接池 创建2*min个连接
//        $this->server->set(
//            [
//                'worker_num' => 1,
//            ]
//        );
        $this->server->on("Start", [$this, "onStart"]);
        $this->server->on("ManagerStart", [$this, "onManagerStart"]);
        $this->server->on("WorkerStart", [$this, "onWorkerStart"]);
        $this->server->on("Request", [$this, "onRequest"]);
        $this->server->on("ShutDown", [$this, "onShutDown"]);
    }


    public function onStart(Server $server)
    {
        //主进程启动
        cli_set_process_title("wolf master");
        $pid = $server->master_pid;
        file_put_contents("./wolf.pid", $pid);
    }

    public function onWorkerStart(Server $server, int $workerId)
    {
        //worker 进程启动
        cli_set_process_title("wolf worker");
        //容器初始化
        BeanFactory::init();
        //获取路由收集器
        $router_collector = BeanFactory::getBean(RouterCollector::class);
        //赋值
        /**@var $router_collector RouterCollector* */
        $this->dispatcher = $router_collector->getRoutes();
    }

    public function onManagerStart(Server $server)
    {
        //manager 管理进程启动
        cli_set_process_title("wolf manager");
    }

    public function onRequest(Request $request, Response $response)
    {
        $myRequest = \Core\http\Request::init($request);
        $myResponse = \Core\http\Response::init($response);
        $routeInfo = $this->dispatcher->dispatch($myRequest->getMethod(), $myRequest->getUri());
        switch ($routeInfo[0]) {
            case Dispatcher::NOT_FOUND:
                $myResponse->setStatus(404);
                $myResponse->end();
                break;
            case Dispatcher::METHOD_NOT_ALLOWED:
                $myResponse->setStatus(405);
                $myResponse->end();
                break;
            case Dispatcher::FOUND:
                $handler = $routeInfo[1];
                $vars = $routeInfo[2];
                $ext_params = [$myRequest, $myResponse];
                $myResponse->setBody($handler($vars, $ext_params));
                $myResponse->end();
                break;
        }
    }


    public function onShutDown(Server $server)
    {
        unlink("./wolf.pid");
        echo "服务已关闭" . PHP_EOL;
    }

    public function run()
    {
        $process = new FilesProcess();
        $this->server->addProcess($process->run());
        $this->server->start();
    }


}
